<script setup lang="ts">
import { request } from '@/api';
import b64toBlob from 'b64-to-blob';
import { closeToast, showLoadingToast, showSuccessToast, showToast, type ActionSheetAction } from 'vant';
import { onMounted, ref } from 'vue';
const showAvatarSheet = ref(false)
 const actions = [
      { name: '拍照' },
      { name: '相册' },
    ];
const showAvatarAction = async (action: ActionSheetAction, index: number) => {
    if (index === 0) {
        const data = await mk.pickerCamera()
        console.log('相机');
        
        onUpdateAvatar(data)
      
        
    }else if (index === 1){
      // 注意await不能忘啊啊啊啊啊，下次检查一定要从头检查
        const data = await mk.pickerPhoto()
        console.log('相册');
        
        onUpdateAvatar(data)
    }
}
// 更新头像
const onUpdateAvatar = async (data: string) => {
  try {
    showAvatarSheet.value = false
    showLoadingToast({ message: '正在上传', duration: 0, forbidClick: true })
    const image = b64toBlob(data, 'image/jpeg')
    console.log(image);
    
    const fd = new FormData()
    fd.append('file', image, Date.now() + '.jpeg')
    const res = await request.post<MkResponse<{ avatar: string }>>('member/profile/avatar', fd)
    profile.value.avatar = URL.createObjectURL(image)
    const user = mk.queryUser()
    user.avatar = res.data.result.avatar
    mk.updateUser(user)
    showToast({ message: '上传成功' })
    console.log('成功');
    
  } catch (err) {
    showToast({ message: '上传失败' })
    console.log('失败');
    
  }
}

// 是否显示生日弹出框
const showBirthday  = ref(false)
// 生日
const birthdayDate = ref(['1976','1','1'])
// 修改生日
const changeBirthday = (data:any) => {
  console.log(data);
  
    profile.value.birthday = data.selectedValues.join('-')
    showBirthday.value = false
}
// 控制城市popup框
const showLocation = ref(false)
// 城市数据
const areaList = ref<AreaColumns>()
onMounted(async () => {
    const data = await mk.getAreaColumns()
    areaList.value = data
    
})
// 修改所在地
const changeLocation = (data:{ selectedValues:number[]}) => {
  const province = areaList.value?.province_list[data.selectedValues[0]]
  const city = areaList.value?.city_list[data.selectedValues[1]]
  const county = areaList.value?.county_list[data.selectedValues[2]]
  profile.value.provinceCode = data.selectedValues[0]
  profile.value.cityCode = data.selectedValues[1]
  profile.value.countyCode = data.selectedValues[2]
  profile.value.fullLocation = `${province} ${city} ${county}`
    showLocation.value = false
}
// 控制职业的popup框
const showProfession = ref(false)
 const columns = [
        { text: '软件工程师', value: '软件工程师' },
        { text: '医生', value: '医生' },
        { text: '教师', value: '教师' },
        { text: '律师', value: '律师' },
        { text: '会计师', value: '会计师' },
        { text: '销售经理', value: '销售经理' },
        { text: '市场营销专员', value: '市场营销专员' },
        { text: '建筑师', value: '建筑师' },
        { text: '护士', value: '护士' },
        { text: '机械工程师', value: '机械工程师' }
    ];
    const changeProfession = ({ selectedValues, selectedOptions, selectedIndexes }:any) => {
      console.log(selectedValues,selectedOptions, selectedIndexes);
      
        profile.value.profession = selectedValues[0]
        showProfession.value = false
    }


// 用户信息
const profile = ref<ProfileInfo>({} as ProfileInfo)
onMounted(async () => {
    showLoadingToast({
        message: '加载中...',
        forbidClick: true,
        duration:0,
    });
    const res = await request.get<MkResponse<ProfileInfo>>('member/profile')
    closeToast()
     profile.value = res.data.result
     birthdayDate.value = profile.value.birthday.split('-')
    
})

const loading = ref(false)
// 提交用户信息
const onsubmit = async () => {
  loading.value = true
  const res = await request.put<MkResponse<ProfileInfo>>('member/profile',profile.value)
    loading.value = false
  mk.updateUser(res.data.result)
  showSuccessToast('修改成功')
  
}
</script>

<template>
  <div class="profile-edit-page">
    <!-- 头像部分 -->
    <div class="avatar">
      <van-image round width="100" height="100" class="avatar-img"
        :src="profile.avatar"
        @click="showAvatarSheet = true">
      </van-image>
      <div class="avatar-btn">
        <span @click="showAvatarSheet = true">修改头像</span>
      </div>
    </div>
    <van-action-sheet
        @select="showAvatarAction"
        v-model:show="showAvatarSheet"
        :actions="actions"
        cancel-text="取消"
        close-on-click-action
    />

    <!-- 中间表单部分 -->
    <van-cell-group>
      <van-field label="账号" readonly v-model="profile.account"></van-field>
      <van-field label="昵称" placeholder="请输入昵称" v-model="profile.nickname"></van-field>
      <van-cell title="性别" class="gender">
        <van-radio-group v-model="profile.gender" :icon-size="16">
          <van-radio name="男">男</van-radio>
          <van-radio name="女">女</van-radio>
          <van-radio name="未知">未知</van-radio>
        </van-radio-group>
      </van-cell>
      <van-field label="生日" v-model="profile.birthday" readonly placeholder="请选择日期"  @click="showBirthday = true"></van-field>
      <van-popup
        v-model:show="showBirthday"
        position="bottom">
        <van-date-picker
        v-model="birthdayDate"
        title="选择日期"
        :min-date="new Date(1970,1,1)"
        :max-date="new Date()"
        @cancel="showBirthday = false"
        @confirm="changeBirthday"
        />
      </van-popup>
      <van-field label="所在地" v-model="profile.fullLocation" readonly placeholder="请选择所在地" @click="showLocation = true"></van-field>
      <van-popup
        v-model:show="showLocation"
        position="bottom">
        <van-area  :area-list="areaList" @cancel="showLocation = false" @confirm="changeLocation"/>
    </van-popup>
      <van-field label="职业" readonly placeholder="请选择职业" @click="showProfession = true" v-model="profile.profession"></van-field>
      <van-popup
        v-model:show="showProfession"
        position="bottom">
        <van-picker
        title="请选择职业"
        :columns="columns"
        @cancel="showProfession = false"
        @confirm="changeProfession"
        />
    </van-popup>
    </van-cell-group>

    <div class="submit">
      <van-button round block type="primary" @click="onsubmit" :loading="loading" loading-text="修改中...">
        保存资料
      </van-button>
    </div>
  </div>
</template>

<style lang="css" scoped>
.avatar {
  padding: 30px;
  text-align: center;
  background-color: var(--mk-white);
}

.avatar-img {
  box-shadow: 0 0 5px var(--mk-gray);
}

.avatar-btn {
  color: var(--mk-linear_end);
  margin-top: 10px;
}

.gender ::v-deep(.van-cell__title) {
  width: 100px;
  flex: none;
}

.van-radio-group {
  display: flex;
  justify-content: space-between;
  height: 36px;
  width: 180px;
}

.submit {
  padding: 16px;
}
</style>